package com.gzu.finalwork.user.service;

import com.gzu.finalwork.user.config.AjaxResult;
import com.gzu.finalwork.entity.user.Addresses;
import com.gzu.finalwork.user.mapper.AddressesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class AddressesService {
    @Autowired
    private AddressesMapper addressesMapper;

    @Autowired
    private AmapService amapService;

    //新增地址
    public Object createAddress(Addresses addresses) {
        if(addresses.getFullAddress() == null || addresses.getFullAddress().equals("")){
            return AjaxResult.error(-1,"地址不能为空");
        }
        if(addresses.getContactName() == null || addresses.getContactName().equals("")){
            return AjaxResult.error(-1,"联系人不能为空");
        }
        if(addresses.getContactPhone() == null || addresses.getContactPhone().equals("")){
            return AjaxResult.error(-1,"联系电话不能为空");
        }
        addresses.setGeocodeStatus(0);
        //判断同类型是否有相同地址
        Addresses oldAddress = addressesMapper.selectDefault(addresses.getFullAddress(),addresses.getIsDefault());
        if(oldAddress != null && Objects.equals(oldAddress.getFullAddress(), addresses.getFullAddress())){
            return AjaxResult.error(-1,"地址已存在");
        }
        int results = addressesMapper.createAddress(addresses);
        Addresses newAddress = addressesMapper.selectDefault(addresses.getFullAddress(),addresses.getIsDefault());
        if (results > 0) {
            // 异步进行地理编码
            geocodeAddressAsync(newAddress.getAddressId(), newAddress.getFullAddress());
            return AjaxResult.success("地址创建成功");
        } else {
            return AjaxResult.error(-1, "地址创建失败");
        }
    }

    //查询所有寄件地址
    public List<Addresses>  selectAllAddress(Long userId,int pageNum,int pageSize){
        int offset = (pageNum - 1) * pageSize;
        List<Addresses> addresses = addressesMapper.selectByUserId(userId,pageSize, offset);
        return addresses;

    }

    //查询用户该类型地址数量
    public Integer selectCountAllAddress(Long userId,Integer isDefault){
        try{
            return addressesMapper.selectCountByUserId(userId,isDefault);
        }catch (Exception e){
            return 0;
        }
    }

    //查询所有收件地址
    public List<Addresses> selectAllReceiveAddress(Long userId,int pageNum,int pageSize){
        int offset = (pageNum - 1) * pageSize;
        List<Addresses> addresses = addressesMapper.getByUserId(userId,pageSize, offset);
        return addresses;
    }

    //删除地址
    public Object deleteAddress(Long addressId){
        if(addressId == null){
            return AjaxResult.error(-1,"地址id不能为空");
        }
        int result = addressesMapper.deleteAddress(addressId);
        if(result == 1){
            return AjaxResult.success("删除地址成功");
        }else{
            return AjaxResult.error(-1,"删除地址失败");
        }
    }
    //更新地址
    public  Object updateAddress(Addresses addresses){
        if(addresses.getAddressId() == null){
            return AjaxResult.error(-1,"地址id不能为空");
        }
        Addresses oldAddress = addressesMapper.selectByAddressId(addresses.getAddressId());
        if(addresses.getFullAddress() == null || addresses.getFullAddress().equals("")){
            addresses.setFullAddress(oldAddress.getFullAddress());
            addresses.setGeocodeStatus(0); // 重置编码状态
            addresses.setLongitude(null);
            addresses.setLatitude(null);
        }
        if(addresses.getContactName() == null || addresses.getContactName().equals("")){
            addresses.setContactName(oldAddress.getContactName());
        }
        if(addresses.getContactPhone() == null || addresses.getContactPhone().equals("")){
            addresses.setContactPhone(oldAddress.getContactPhone());
        }
        if(addresses.getIsDefault() == null){
            addresses.setIsDefault(oldAddress.getIsDefault());
        }
        if(addresses.getUserId() == null){
            addresses.setUserId(oldAddress.getUserId());
        }
        addresses.setUpdatedAt(LocalDateTime.now());
        int result = addressesMapper.updateAddress(addresses);
        if (result > 0) {
            // 如果地址变化，异步重新编码
            if (oldAddress != null && !oldAddress.getFullAddress().equals(addresses.getFullAddress())) {
                geocodeAddressAsync(addresses.getAddressId(), addresses.getFullAddress());
            }
            return AjaxResult.success("地址更新成功");
        } else {
            return AjaxResult.error(-1, "地址更新失败");
        }
    }

    //设置默认地址
    public Object setDefaultAddress(Long addressId,Long userId){
        if(addressId == null){
            return AjaxResult.error(-1,"地址id不能为空");
        }
        //先将其他地址的默认值设置为0
         addressesMapper.updateByUserId(userId);
        //再将当前地址的默认值设置为1
        int result = addressesMapper.updateDefaultByAddressId(addressId);
        if(result == 1){
            return AjaxResult.success("设置默认地址成功");
        }else{
            return AjaxResult.error(-1,"设置默认地址失败");
        }
    }

    // 异步地理编码
    @Async
    public void geocodeAddressAsync(Long addressId, String fullAddress) {
        List<String> geocodeResult = amapService.geocode(fullAddress);
        if (geocodeResult != null && geocodeResult.size() >= 2) {
            // 直接从List中获取经度和纬度
            String longitudeStr = geocodeResult.get(0);
            String latitudeStr = geocodeResult.get(1);
            Double longitude = Double.parseDouble(longitudeStr.trim());
            Double latitude = Double.parseDouble(latitudeStr.trim());

            // 验证坐标范围（中国境内大致范围）
            if (longitude >= 73.0 && longitude <= 135.0 &&
                    latitude >= 18.0 && latitude <= 54.0) {

                // 更新地址坐标
                Addresses updateAddress = new Addresses();
                updateAddress.setAddressId(addressId);
                updateAddress.setLongitude(longitude);
                updateAddress.setLatitude(latitude);
                updateAddress.setGeocodeStatus(1); // 编码成功
                updateAddress.setUpdatedAt(LocalDateTime.now());

                addressesMapper.updateAddress(updateAddress);
            } else {
                updateGeocodeStatus(addressId, 2);
            }
        } else {
            updateGeocodeStatus(addressId, 2);
        }
    }

    /**
     * 更新地理编码状态
     */
    private void updateGeocodeStatus(Long addressId, Integer status) {
        Addresses updateAddress = new Addresses();
        updateAddress.setAddressId(addressId);
        updateAddress.setGeocodeStatus(status);
        updateAddress.setUpdatedAt(LocalDateTime.now());
        addressesMapper.updateAddress(updateAddress);

    }

//    /**
//     * 手动重新地理编码
//     */
//    public Object reGeocodeAddress(Long addressId) {
//        if (addressId == null) {
//            return AjaxResult.error(400, "地址ID不能为空");
//        }
//        Addresses address = addressesMapper.selectByAddressId(addressId);
//        if (address == null) {
//            return AjaxResult.error(404, "地址不存在");
//        }
//        geocodeAddressAsync(addressId, address.getFullAddress());
//        return AjaxResult.success("重新地理编码已启动");
//    }

}